var util = require('../../utils/util.js');
Component({
  properties: {
    //控制显示
    show: {
      type: Boolean,
      value: false
    },
    excludeIds: {
      type: String,
      value: ''
    }
  },
  data: {
    API_BASE_URL: util.API_BASE_URL,
    keyword: '',
    showClear: false,
    list: [],
    selectList: [],
    pageNo: 1,
    pageSize: 15,
    totalPage: 1, //总页数
    lastClickTime: 0,
    countyIndex: 0,
    countyList: [
      {
        name: '龙岩市',
        code: ''
      }, {
        name: '新罗区',
        code: '350802'
      }, {
        name: '永定区',
        code: '350803'
      }, {
        name: '上杭县',
        code: '350823'
      }, {
        name: '武平县',
        code: '350824'
      }, {
        name: '长汀县',
        code: '350821'
      }, {
        name: '连城县',
        code: '350825'
      }, {
        name: '漳平市',
        code: '350881'
      }
    ],
    tagIndex: 0,
    tagList: [],
    sortIndex: 0,
    sortList: [
      {
        type: 1,
        name: '综合'
      }, {
        type: 2,
        name: '热度'
      }, {
        type: 3,
        name: '距离'
      },
    ],
    bqmcMap: {
      '革命党史': '1',
      '红色资源': '2',
      '绿色生态': '3',
      '红色经典': '4',
      '古色文化': '5',
      '金色产业': '6'
    },
    bqysMap: {
      '革命党史': '#B07575',
      '红色资源': '#AC3C3C',
      '绿色生态': '#88A08B',
      '红色经典': '#AD3C3C',
      '古色文化': '#83705B',
      '金色产业': '#D8B36C'
    },
    latitude: '',
    longitude: '',
    sort_rule: 'desc',
    scrollTop: 0, // 滚动条位置
  },
  pageLifetimes: {
    show() {
      // this.init();
    },
  },
  methods: {
    //初始化
    async init(e) {
      await new Promise((resolve, reject) => {
        wx.getLocation({
          type: 'gcj02',
          success: (res) => {
            this.setData({
              latitude: res.latitude,
              longitude: res.longitude
            });
            resolve();
          },
          fail: (err) => {
            console.log(err);
            resolve(); // 即使失败也继续后续流程（如需强制获取可用 reject）
          }
        });
      });
      this.setData({
        list: [],
        selectList: [],
        pageNo: 1,
        totalPage: 1
      })
      await this.queryZydflByPage();
      this.queryResourceByPage()
    },
    //关闭弹窗
    closePopup() {
      this.setData({ show: false })
    },
    //关键字搜索
    onSearch() {
      this.setData({
        countyIndex: 0,
        tagIndex: 0,
        sortIndex: 0,
        pageNo: 1,
        totalPage: 1,
        scrollTop: 0
      })
      this.queryResourceByPage()
    },
    onInput(e) {
      const value = e.detail.value;
      this.setData({
        showClear: value !== ''
      });
    },
    clearInput() {
      this.setData({
        countyIndex: 0,
        tagIndex: 0,
        sortIndex: 0,
        pageNo: 1,
        totalPage: 1,
        scrollTop: 0,
        keyword: '',
        showClear: false
      });
      this.queryResourceByPage();
    },
    // 点击排序
    onClickSort(e) {
      const { index } = e.currentTarget.dataset;
      const { sortIndex } = this.data;
      if (sortIndex != index) {
        this.setData({
          sortIndex: index,
          pageNo: 1,
          scrollTop: 0,
          sort_rule: 'desc'
        });
      } else {
        this.setData({
          pageNo: 1,
          scrollTop: 0,
          sort_rule: this.data.sort_rule == 'asc' ? 'desc' : 'asc'
        });
      }
      this.queryResourceByPage();
    },
    // 选择标签
    onClickTag(e) {
      const { index } = e.currentTarget.dataset;
      const { tagIndex } = this.data;
      if (tagIndex != index) {
        this.setData({
          tagIndex: index,
          pageNo: 1,
          scrollTop: 0
        });
        this.queryResourceByPage();
      }
    },
    // 选择区县
    onClickCounty(e) {
      const { index } = e.currentTarget.dataset;
      const { countyIndex } = this.data;
      if (countyIndex != index) {
        this.setData({
          countyIndex: index,
          pageNo: 1,
          scrollTop: 0
        });
        this.queryResourceByPage();
      }
    },
    //添加
    add() {
      const now = Date.now();
      if (now - this.data.lastClickTime < 1000) { // 限制1秒内只能点击一次
        return;
      }
      this.setData({
        show: false,
        lastClickTime: now
      })
      let selectList = [];
      this.data.selectList.forEach(item => {
        delete item.billid
        selectList.push(item)
      })
      // this.triggerEvent('compute', { selectList });
    },
    //点击卡片
    handleCard(e) {
      const { item } = e.currentTarget.dataset;
      this.triggerEvent('handleSelectZyd', { data: item });
      this.setData({
        show: false
      })
    },
    //视口滚动到底部触发
    lower() {
      let { pageNo, totalPage } = this.data;
      //如果还没到最后一页，就继续请求
      if (pageNo <= totalPage) {
        this.queryResourceByPage()
      }
    },
    //查询标签信息
    async queryZydflByPage() {
      let _this = this;
      return util.request('itf/common/hongpei/resource/queryZydflByPage.json', {
        billtype: 'zyfl',
        pageSize: '20',
        pageNo: "1"
      }).then(res => {
        if (res.success) {
          let records = res.records;
          let tagList = [{
            "id": "",
            "name": "全部"
          }];
          if (records) {
            for (let i = 0; i < records.length; i++) {
              let item = records[i];
              tagList.push({
                id: item.billid,
                name: item.name
              });
            }
          }
          _this.setData({ tagList })
        } else {
          util.showMsg({ msg: "获取资源分类失败！" });
        }
      });
    },
    //查询资源点数据
    queryResourceByPage() {
      const _this = this;
      let {
        keyword,
        list,
        latitude,
        longitude,
        sortList,
        sortIndex,
        tagList,
        tagIndex,
        countyList,
        countyIndex,
        pageNo,
        pageSize,
        sort_rule,
        excludeIds
      } = this.data;

      wx.showLoading({
        title: '加载中...',
        mask: true
      })
      util.request('/itf/common/hongpei/resource/queryResourceByPage.json', {
        keyword,
        county: countyList[countyIndex].code,
        zyfl_pk: tagList[tagIndex].id,
        sort_type: sortList[sortIndex].type,
        sort_rule,
        longitude,
        latitude,
        pageNo,
        pageSize,
        excludeIds,
        type: 'user'
      }).then(res => {
        if (res.success) {
          let { records, totalPage } = res;
          records.forEach(item => {
            item.is_check = 'N';
            item.banner_xqy = item.banner_xqy ? item.banner_xqy.split(",")[0] : '';
            _this.data.selectList.forEach(seleted => {
              if (item.billid == seleted.billid) {
                item.is_check = 'Y';
              }
            })
          })

          let newList = pageNo === 1 ? records : list.concat(records);
          this.setData({
            list: newList,
            totalPage: pageNo === 1 ? totalPage : this.data.totalPage,
            pageNo: pageNo + 1
          });
        } else {
          util.showMsg({ msg: res.message || res.msg })
        }
        wx.hideLoading();
      });
    }
  }
})